$(document).ready(function() {	
		//导航栏切换
		$("#lifoodmanage").addClass("current").siblings().removeClass("current");
		//请求订单列表业务数据  时间倒叙
	    $.ajax({
	        type: "POST",
	        url: "foodClassList",
	        data: {page:$("#currentPage").val(),pageSize:7,ordertype:0,aid:$("#aid").val()},
	        dataType: "json",
	        success: function(data){
	        		//加载业务数据
	    	        ajaxFoodClassCallBack(data);	
                    //向分页标签里添加页数
                    var pageNumber = createPageNumberTag($("#currentPage").val(),$("#pageCount").val());
                    $("#prev").after(pageNumber);
	        }
	    });
		
		//绑定所有的关闭图片点击关闭当前的层
		$(".tdtitle span").each(function(){
			$(this).on("click",function(){
				$(this).parents(".tdpopup").addClass("hide");
			});
		});
		
		//菜品类别层显示事件
		$("#addFoodClass").on("click",function(){
			$("#addFoodClassDiv .tstext").val("");
			$("#addFoodClassDiv").removeClass("hide");
		});
		
		//菜品类别添加事件
		$("#saveFoodClassBtn").on("click",function(){
			var  addFoodClassName =$.trim($("#addFoodClassName").val());
			if(addFoodClassName.length==0){
				layer.tips("菜品分类名称不能为空", "#addFoodClassName");
				return ;
			}else if(addFoodClassName.length>10){
				layer.tips("菜品分类名称长度不能为大于10", "#addFoodClassName");
				return ;
			}else{
				$.ajax({
			        type: "POST",
			        url: "saveFoodClass",
			        data: {classname:$("#addFoodClassDiv .tstext").val(),aid:$("#aid").val()},
			        dataType: "json",
			        async: false,
			        success: function(data){
						if(data.state==1){
							layer.msg("菜品分类添加成功",{icon: 1,time:2500});
							$("#addFoodClassDiv").addClass("hide");
							foodClassAjaxRequest($("#currentPage").val());
						}else if(data.state==2){
							layer.tips("菜品分类名称已被使用", "#addFoodClassName");
						}else{
							layer.msg("菜品分类添加失败",{icon: 5,time:2500});
						}
			        }
			    });	
			}
		});
		
		//菜品类别添加事件
		$("#modifyFoodClassBtn").on("click",function(){
			var  modifyFoodClassName = $.trim($("#modifyFoodClassName").val());
			if(modifyFoodClassName.length==0){
				layer.tips("菜品分类名称不能为空", "#modifyFoodClassName");
				return ;
			}else if(modifyFoodClassName.length>10){
				layer.tips("菜品分类名称长度不能为大于10", "#modifyFoodClassName");
				return ;
			}else{
				$.ajax({
			        type: "POST",
			        url: "saveFoodClass",
			        data: {classname:$("#modifyFoodClassDiv .tstext").val(),fid:$("#modifyFoodClassDiv #fcid").val(),aid:$("#aid").val()},
			        dataType: "json",
			        success: function(data){
						if(data.state==1){
							layer.msg("菜品分类修改成功",{icon:1,time:2500});
							$("#modifyFoodClassDiv").addClass("hide");
							foodClassAjaxRequest($("#currentPage").val());
						}else if(data.state==2){
							layer.tips("菜品分类名称已被使用", "#modifyFoodClassName");
						}else{
							layer.msg("菜品分类修改失败",{icon:5,time:2500});
						}
			        }
			    });	
			}
		});
		
		//上传图片
		$("#bigpic").change(function(){	
			var imgs = $("#bigpic").val().split(".");
			if(imgs[1]!="jpg"&&imgs[1]!="png"&&imgs[1]!="jpeg"&&imgs[1]!="bmp"){
				layer.msg("图片仅支持jpg、png、jpeg、bmp格式",{icon:5,time:2500});
				return;
			}
			$("#form1").ajaxSubmit({  
					url:"fileUpload", 
					type:"POST", 
					dataType:"json", 
					data:{ aid:$("#aid").val()},
					success: function(data){ 
						$(".imgpic").removeClass("hide");
						$(".imgpic").attr("src",data.response.picurl);  //图片全路径
						$("#imgUrl").val(data.response.fileurl);	//大图图片路径
						$("#breUrl").val(data.response.breurl);	//缩略图图片路径
						$("#userImage").val(""); 
						layer.msg("图片上传成功，提交后生效！",{icon:1,time:2500});
						} 
					});  
			return false;
		});
		
		
		//checkbox的点击事件
		$("#atag").on("click",function(){
			if($(this).prop("checked")=="true"){     
			    $(this).prop("checked",false);  
			}else if($(this).prop("checked")=="false"){     
			    $(this).prop("checked",true);
			}     	
		});
		
		
		//菜品保存点击事件
		$("#saveFoodBtn").on("click",function(){
			//数据校验
			if($("#foodid").val().length==0){
				if($("#datastatus  option:selected").val()==3){
					layer.tips("新增菜品时状态不能为下架", "#datastatus");
					return ;
				}
			}
			var  floatReg = new RegExp("/^\d+\.\d\d$/");   //浮点型小数
			var  numberReg =new RegExp("/^[0-9]*[1-9][0-9]*$/");  //正整数
			var  foodname = $.trim($("#foodname").val());
			var  datastatus = $("#datastatus  option:selected").val();   //菜品状态
			var foodid = $("#foodid").val();  //菜品状态
			if($("#atag").prop("checked")){   //设置为广告位
				if(foodid.length!=0&&datastatus==3){      //
					layer.msg("广告位的菜品，必须要保留不得下架，只可替换",{icon:5,time:2000});
					return ;
				}
			}
			if(foodname.length==0){
				layer.tips("菜品名称不能为空", "#foodname");
				return ;
			}else  if(foodname.length>10){
				layer.tips("菜品名称长度不能为大于10", "#foodname");
				return ;
			}else  if(foodname.length==0){
				layer.tips("菜品价格不能为空", "#cprice");
				return;
			}else if(isPriceFormat($.trim($("#cprice").val()))){
				layer.tips("菜品价格格式输入不正确,", "#cprice");
				return;
			}else if($.trim($("#cprice").val())==0){
				layer.tips("菜品价格必须大于0", "#cprice");
				return;
		    }else if($("#imgUrl").val().length==0){
				layer.tips("菜品展示图不能为空", "#bigpic");
				return;
				//注释于2015年7月23日10:31:10 
				/**layer.confirm('您未上传菜品展示图，现在保存？', {
				    btn: ['确定','取消'], //按钮
				    shade: false //不显示遮罩
				}, function(){
					saveFoodSubmit();
				}, function(){
				   return ;
				});***/
			}else{
				saveFoodSubmit();
			}
		});
		
		//绑定批量删除的点击事件
		$("#delBatchFoodClass").on("click",function(){
			var  foodids="";
			//获取所有选中的checkbox
			if($(".cpgl-box :checkbox:checked").length==0){
				layer.msg("未选中任何菜品",{icon:5,time:1200});
				return;
			}
			$(".cpgl-box :checkbox:checked").each(function(){
				foodids+=$(this).parents("tr").attr("id").substr(5)+";";
			});
			layer.confirm('确认删除当前的选中项？', {
			    btn: ['确认','取消'], //按钮
			    shade: false //不显示遮罩
			}, function(){
				$.ajax({
			        type: "POST",
			        url: "delFoodOrFoodClass",
			        data: {ids:foodids,type:1, aid:$("#aid").val()},
			        dataType: "json",
			        success: function(data){
						if(data.state==1){
							layer.msg("菜品删除成功",{icon:1,time:2500});
							var  foods = foodids.split(";");
							$.each(foods,function(item){
								$("#food_"+foods[item]).remove();
							});
						}else if(data.state==3){ 
							layer.msg("广告位的菜品，必须要保留不得删除，只可替换",{icon:5,time:2500});
						}else{
							layer.msg("菜品删除失败",{icon:5,time:2500});
						}
			        }
			    });	
			});
		});
 });
 

//保存数据
function  saveFoodSubmit(){
	var  foodclassid=$("#oldfoodclassid").val();
	var  type =$("#foodid").val().length!=0?2:1;  //type=1  新增   type=2  修改
	$.ajax({
        type: "POST",
        url: "saveFood",
        data: {
        	 id:$("#foodid").val(),
        	 fid:$("#foodclassid  option:selected").val(),
        	 datastatus:$("#datastatus  option:selected").val(),
        	 foodname:$("#foodname").val(),
        	 cprice:$("#cprice").val(),
        	 bigpic:$("#imgUrl").val(),
        	 smallpic:$("#breUrl").val(),
        	 num:$("#num").text(),
        	 atag:$("#atag").prop("checked")==true?1:0,
        	 aid:$("#aid").val()},
        dataType: "json",
        success: function(data){
			if(data.state==1){
				layer.msg("菜品保存成功",{icon:1,time:2500});
				$("#modifyFoodDiv").addClass("hide");
				if($("#atag").prop("checked")){
					$("b.fr").remove();
				}
				foodCallback(foodclassid,type);
				
			}else if(data.state==2){
				layer.tips("菜品名称已被使用", "#foodname");
			}else{
				layer.msg("菜品保存失败",{icon:5,time:2500});
			}
        }
    });	
}


/**
 * 新增菜品或修改菜品后的回调
 * type=1  新增   type=2  修改
 */
function  foodCallback(foodclassid,type){
	//异步请求数据
	$.ajax({
        type: "POST",
        url: "foodList",
        data: {foodclassid:foodclassid,aid:$("#aid").val()},
        dataType: "json",
        success: function(data){
			if(data.state=1){
				$("#foodList_"+foodclassid).find("tr:gt(0)").remove();
				$("#foodList_"+foodclassid).children("table").append(ajaxFoodCallBack(data));
				if(type==1){  //新增菜品 需要加菜品数
					$("#foodnum_"+foodclassid).text($("#foodnum_"+foodclassid).text()*1+1);
				}
			}else{
				layer.msg("暂无响应的数据",{icon:5,time:2500});
			}
        }
    });
}

//删除菜品分类或菜品 type 1 --- 删除菜品    type=2  --删除菜品分类
function  delFoodOrFoodClass(ids,foodclassid,type){
	layer.confirm('确认删除当前的选中项？', {
	    btn: ['确认','取消'], //按钮
	    shade: false //不显示遮罩
	}, function(){
		$.ajax({
	        type: "POST",
	        url: "delFoodOrFoodClass",
	        data: {ids:ids,type:type,aid:$("#aid").val()},
	        dataType: "json",
	        success: function(data){
				if(data.state==1){
					layer.msg("删除数据成功",{icon:1,time:2500});
					if(type==1){   //删除菜品
						$("#food_"+ids).remove();
						$("#foodnum_"+foodclassid).text($("#foodnum_"+foodclassid).text()*1-1);
					}else if(type==2){  //删除菜品分类
						$("#"+ids).remove();
					}
				}else if(data.state==2){
					layer.msg("请将此分类下的所有菜品分类改至其他分类再进行删除",{icon:5,time:2500});
				}else if(data.state==3){ 
					layer.msg("广告位的菜品，必须要保留不得删除，只可替换",{icon:5,time:2500});
	        	}else{
					layer.msg("暂无响应的数据",{icon:5,time:2500});
				}
	        }
	    });
	}, function(){
	    
	});
}


//打开修改菜品分类层  获取菜品分类信息
function  modifyFoodClass(id){
	$.ajax({
        type: "POST",
        url: "getFoodClassInfo",
        data: {fcid:id,aid:$("#aid").val()},
        dataType: "json",
        success: function(data){
			if(data.state==1){
				$("#modifyFoodClassDiv .tstext").val(data.foodClass.classname);
				$("#modifyFoodClassDiv #fcid").val(data.foodClass.fid);
				$("#modifyFoodClassDiv").removeClass("hide");
			}else{
				layer.msg("获取菜品分类信息失败",{icon:5,time:2500});
			}
        }
    });	
}	


//展开或折叠菜品列表
function  showFoodList(obj){
	var fcid=$(obj).parents("ol").attr("id");
	if($(obj).children("b").hasClass("jia")){  //展开显示列表
		$(obj).children("b").removeClass("jia");
		$(obj).children("b").addClass("jian");
		//如果菜品数据层已有就直接显示
		if($("#foodList_"+fcid).hasClass("hide")){
		   $("#foodList_"+fcid).removeClass("hide");
		}else{
			//异步请求数据
			$.ajax({
		        type: "POST",
		        url: "foodList",
		        data: {foodclassid:fcid,aid:$("#aid").val()},
		        dataType: "json",
		        success: function(data){
					if(data.state==1){
						$(obj).parents("ol").after(createFoodHeadTR(fcid));   //列表头部
						$("#foodList_"+fcid).children("table").append(ajaxFoodCallBack(data));
					}else{
						layer.msg("暂无响应的数据",{icon:5,time:2500});
					}
		        }
		    });	
		}
	}else{  //折叠列表
		$(obj).children("b").removeClass("jian");
		$(obj).children("b").addClass("jia");
		$("#foodList_"+fcid).addClass("hide");
	}
}
	

//添加菜品
function  addFood(foodclassid){
	$.ajax({
        type: "POST",
        url: "getFoodInfo",
        data: {fcid:foodclassid,aid:$("#aid").val()},
        dataType: "json",
        success: function(data){
        	if(data.state==1){
				//显示层
				$("#modifyFoodDiv").removeClass("hide");
				$("#foodtitle").text("新增菜品");
				$("#datastatusDiv").addClass("hide");
				$("#foodclassid").attr("disabled","disabled");
				showModifyFoodDiv(data);
        	}else{
			   layer.msg("暂无响应的数据",{icon:5,time:2500});
        	}
        }
	});
}


///添加或修改菜品层打开  id==0 表示新增
function  modifyFood(fid){
	if(fid!=0){  //修改异步请求数据
		$.ajax({
	        type: "POST",
	        url: "getFoodInfo",
	        data: {fid:fid,aid:$("#aid").val()},
	        dataType: "json",
	        success: function(data){
				if(data.state==1){
					$("#foodtitle").text("编辑菜品");
					$("#datastatusDiv").removeClass("hide");
					$("#foodclassid").removeAttr("disabled");
					showModifyFoodDiv(data);
				}else{
					layer.msg("暂无响应的数据",{icon:5,time:1200});
				}
	        }
	    });
	}
}

function  showModifyFoodDiv(data){
	//显示层
	$("#modifyFoodDiv").removeClass("hide");
	//字段的清空
	$("#fileUrl").val("");
	$("#imgUrl").val("");
	$("#breUrl").val("");
	$(".imgpic").attr("src","");
	$("#atag").prop("checked",false);
	 $("#atag").removeAttr("disabled");
	$("#foodclassid").html("");
	//创建菜品类别
	$("#foodclassid").append(createFoodClassList(data));
	$("#datastatus option").each(function(){
		if($(this).val()==1){
			$(this).attr("selected",true);
		}	
		if($(this).val()==3){
			$(this).attr("selected",false);
		}
	});
	
	//填充数据
	$("#foodid").val(data.food.id);
	$("#foodname").val(data.food.foodname);
	$("#cprice").val(data.food.cprice);
	if(data.food.atag==1){
	    $("#atag").prop("checked",true);
	    $("#atag").attr("disabled","disabled");
	}
	$("#num").text(data.food.num);
	$("#foodclassid option").each(function(){
		if($(this).val()==data.food.fid){
			$(this).attr("selected",true);
		}	
	});
	$("#oldfoodclassid").val(data.food.fid);
	$("#datastatus option").each(function(){
		if($(this).val()==data.food.datastatus){
			$(this).attr("selected",true);
		}	
	});
	if(data.food.bigpic.length!=0){
		//显示图片
		$(".imgpic").attr("src",data.fileUrl+data.food.bigpic);
		$("#imgUrl").val(data.food.bigpic);
		$(".imgpic").removeClass("hide");
	}else{
		$(".imgpic").addClass("hide");
	}
	if(data.food.smallpic.length!=0){
		$("#breUrl").val(data.food.smallpic);
	}
}


function createFoodClassList(data){
	var result = data.foodClasses;
	var insetViewData = ""; //视图数据  
	$.each(result, function(index, items) {
		insetViewData += "<option value='"+items.fid+"'>"+items.classname+"</option>";
	});
	return insetViewData;
}


//回调函数
function ajaxFoodClassCallBack(data){
	//总页数，当前页赋值给隐藏域
	$("#pageCount").val(data.pageCount);
	$("#currentPage").val(data.currentPage);
	$("#sellerid").val(data.sellerid);
	var result = data.foodClassList;
	var insetViewData = ""; //视图数据
	if(result.length!=0){
		$.each(result, function(index, items) {
			insetViewData += createFoodClassTR(items);
		});
	}
	$("#pagediv").html(insetViewData);
}

//返回菜品列表
function ajaxFoodCallBack(data){
	var result = data.foodList;
	var insetViewData = ""; //视图数据  
	if(result.length!=0){
		$.each(result, function(index, items) {
			insetViewData += createFoodTR(items);
		});
	}
	return insetViewData;
}


function  isPriceFormat(price){
	var  priceReg =new RegExp("/^\d+(\.\d+)?$/"); 
	if(priceReg.test(price)){
		return  true;
	}else{
		return false;
	}
}


//分页设置1，首页，2上一页，3下一页，4尾页
function getCurrPage(currNum) {	
	//上一页
	var front = Number($("#currentPage").val())-Number(1);
	//下一页
	var next  = Number($("#currentPage").val())+Number(1);
	if(1 == currNum) {
		$("#currentPage").val(1);
	}else if(2 == currNum) {
		if(front <= 0) {//上一页小于第一页
			$("#currentPage").val(1);
			layer.msg("已经到了首页啦");
		}else{
			$("#currentPage").val(front);
		}
	}else if(3 == currNum) {
		if(next > Number($("#pageCount").val())) {//下一页大于最后一页
			$("#currentPage").val($("#pageCount").val());
			layer.msg("已经到了尾页啦");
		}else{
			$("#currentPage").val(next);
		}
	}else if(4 == currNum) {
		$("#currentPage").val($("#pageCount").val());
	}
	foodClassAjaxRequest($("#currentPage").val());

}	
//跳转到指定的页面
function gotoMyPage() {
	var myPage = Number($("#myPage").val());
	var min = 1 ;
	var max = Number($("#pageCount").val());
	if(myPage == null || myPage == "") {
		layer.msg("跳转的页码未填！");
	}else if(min > myPage || max < myPage ){
		layer.msg("跳转的页面超出范围了！");
	}else{
		foodClassAjaxRequest(myPage);
	}
}	
//动态生成页数
function createPageNumberTag(currentPage , pageCount) {
	var pageNumber = "<span id='pagespan'>";
	var tempbegin = 0;
	var tempend = 0;
	if(currentPage <= 4 || pageCount <= 9) {//当前页小于4或总页数小于9，全部显示
		tempbegin = 1;
		if(pageCount<=9) {
			tempend=pageCount;
		}else{
			tempend=9;
		}
	}else{
		if(currentPage <= Number(pageCount)-Number(4)){//当前页小于总页数-3
			tempbegin = Number(currentPage)-Number(4);
			tempend   = Number(currentPage)+Number(4);
		}else {
			if(currentPage > Number(pageCount)-Number(4)){//当前页大于总页数-3:到了末尾
				tempbegin = Number(pageCount)-Number(8);
				tempend   = pageCount;
			}
		}
	}
	for(var i = tempbegin ; i <= tempend; i++) {
		if(currentPage == i){
			pageNumber += "<a id='page"+i+"'  href='javascript:foodClassAjaxRequest("+i+")' class='on'>"+i+"</a>";
		}else{
			pageNumber += "<a id='page"+i+"' href='javascript:foodClassAjaxRequest("+i+")'>"+i+"</a>";
		}
	}
	pageNumber += "</span>";
	return pageNumber;
}

//异步请求订单数据
function foodClassAjaxRequest(currentPage){
	//移除页码
	$("#pagespan").remove();
	//重新加载页码
    var pageNumber = createPageNumberTag(currentPage,$("#pageCount").val());
	//alert(pageNumber);
    $("#prev").after(pageNumber);
	//点击页数颜色变化
	$(".page-num > #pagespan > .on").removeClass("on");
	$("#page"+currentPage).addClass("on");
	//请求当页数据
    $.ajax({
        type: "POST",
        url: "foodClassList",
        data: {page:currentPage,pageSize:7,ordertype:0,aid:$("#aid").val()},
        dataType: "json",
        success: function(data){
        	 ajaxFoodClassCallBack(data);	
        }
    });
}


//创建菜品类别的每一行		
function createFoodClassTR(obj) {
	var tr = "<ol class='cpgldatas' id='"+obj.fid+"'> <li class='fl datassp' onclick='showFoodList(this)'><b class='jia'></b></li>";
	tr += "<li class='fl datassp2'>" + obj.classname + "</li>";		
	tr += "<li class='fl'><label id='foodnum_"+obj.fid+"'>" + obj.foodnum + "</label></li>";		
	tr += "<li class='fl'><a href='javascript:addFood("+obj.fid+")' class='fl addbtn'>添加菜品</a>";
	tr += "<a href='javascript:modifyFoodClass("+obj.fid+")'  class='fl addbtn'>编辑</a>";
	tr += "<a href='javascript:delFoodOrFoodClass("+obj.fid+",0,2)' class='fl addbtn'>删除</a></li>";		
	tr += "</ol>";
	return tr;
}	

//菜品列表头部
function  createFoodHeadTR(foodclassid){
	var  tr="<div class='cpdatas' id='foodList_"+foodclassid+"'><table><tr><th width='68'>编号</th> <th width='126'>菜品名称</th><th width='78'>菜品状态</th>";
	tr += "<th width='126'>菜品价格（元）</th>";
	tr += "<th width='96'>已售份数</th>";
	tr += "<th width='160'>操作</th></tr></table></div>";
	return  tr;
}


//创建菜品的每一行
function createFoodTR(obj){
	var tr = "<tr id='food_"+obj.id+"'><td><input type='checkbox'><span><span></td>";   //第一行编号
	tr += "<td class='cpm'>"+obj.foodname;   //菜品名称
	if(obj.atag==1){
		tr += "<b class='fr'></b>"; 
	}
	tr += "</td>"; 
	tr +="<td>";
	if(obj.datastatus==1){  //菜品状态
		tr += "<span class='up'>上架</span>";	
	}else if(obj.datastatus==3) {
		tr += "<span class=''>下架</span>";	
	}
	tr +="</td>";
	tr += "<td class='jg'>"+obj.cprice+"</td>";    //菜品价格	
	tr += "<td>"+obj.sellnum+"</td>";  //菜品已售数量
	tr += "<td><a href='javascript:modifyFood("+obj.id+")' class='fl addbtn'>编辑</a>";
	tr += "<a href='javascript:delFoodOrFoodClass("+obj.id+","+obj.fid+",1)' class='fl addbtn'>删除</a></td>";		
	tr += "</tr>";
	return tr;
}
